package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"w3c/mysession"
	"w3c/route"

	mysqldata "w3c/model"

	_ "github.com/astaxie/session/providers/memory"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gorilla/mux"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func handler(w http.ResponseWriter, r *http.Request) {

	err := route.Dispatcher(w, r)
	if err != nil {
		fmt.Fprint(w, err)
		return
	}
	mysession.SetHttpparams(w, r)

	noneedCheck, _ := mysession.In([]interface{}{"/", "/login", "/test"}, r.RequestURI)

	if !noneedCheck {
		fmt.Println("need authoroize")
		//mysession.CheckLogin(w, r)
	}

}
func init() {
	return
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       "root:root@tcp(127.0.0.1:3306)/gotour?charset=utf8&parseTime=True&loc=Local",
		DefaultStringSize:         256,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	}), &gorm.Config{})

	mysqldata.DB = db
	if err != nil {
		log.Fatal("fail to connect mysql")
	}

}
func main() {
	r := mux.NewRouter()
	r.Use(loggingMiddleware)
	r.HandleFunc("/", handler)
	r.HandleFunc("/{*}", handler)

	srv := &http.Server{
		Handler: r,
		Addr:    "127.0.0.1:9090",
		// Good practice: enforce timeouts for servers you create!
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	log.Fatal(srv.ListenAndServe())

}

func loggingMiddleware(next http.Handler) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mysession.SetHttpparams(w, r)

		// Do stuff here
		log.Println(r.RequestURI)

		next.ServeHTTP(w, r)
	})
}
